{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# nurse_rostering"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/nurse_rostering.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/contrib/nurse_rostering.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "  Nurse rostering in Google CP Solver.\n",
    "\n",
    "  This is a simple nurse rostering model using a DFA and\n",
    "  my decomposition of regular constraint.\n",
    "\n",
    "  The DFA is from MiniZinc Tutorial, Nurse Rostering example:\n",
    "  - one day off every 4 days\n",
    "  - no 3 nights in a row.\n",
    "\n",
    "\n",
    "  This model was created by Hakan Kjellerstrand (hakank@gmail.com)\n",
    "  Also see my other Google CP Solver models:\n",
    "  http://www.hakank.org/google_or_tools/\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "from ortools.constraint_solver import pywrapcp\n",
    "from collections import defaultdict\n",
    "\n",
    "#\n",
    "# Global constraint regular\n",
    "#\n",
    "# This is a translation of MiniZinc's regular constraint (defined in\n",
    "# lib/zinc/globals.mzn), via the Comet code refered above.\n",
    "# All comments are from the MiniZinc code.\n",
    "# '''\n",
    "# The sequence of values in array 'x' (which must all be in the range 1..S)\n",
    "# is accepted by the DFA of 'Q' states with input 1..S and transition\n",
    "# function 'd' (which maps (1..Q, 1..S) -> 0..Q)) and initial state 'q0'\n",
    "# (which must be in 1..Q) and accepting states 'F' (which all must be in\n",
    "# 1..Q).  We reserve state 0 to be an always failing state.\n",
    "# '''\n",
    "#\n",
    "# x : IntVar array\n",
    "# Q : number of states\n",
    "# S : input_max\n",
    "# d : transition matrix\n",
    "# q0: initial state\n",
    "# F : accepting states\n",
    "\n",
    "\n",
    "def regular(x, Q, S, d, q0, F):\n",
    "\n",
    "  solver = x[0].solver()\n",
    "\n",
    "  assert Q > 0, 'regular: \"Q\" must be greater than zero'\n",
    "  assert S > 0, 'regular: \"S\" must be greater than zero'\n",
    "\n",
    "  # d2 is the same as d, except we add one extra transition for\n",
    "  # each possible input;  each extra transition is from state zero\n",
    "  # to state zero.  This allows us to continue even if we hit a\n",
    "  # non-accepted input.\n",
    "\n",
    "  # Comet: int d2[0..Q, 1..S]\n",
    "  d2 = []\n",
    "  for i in range(Q + 1):\n",
    "    row = []\n",
    "    for j in range(S):\n",
    "      if i == 0:\n",
    "        row.append(0)\n",
    "      else:\n",
    "        row.append(d[i - 1][j])\n",
    "    d2.append(row)\n",
    "\n",
    "  d2_flatten = [d2[i][j] for i in range(Q + 1) for j in range(S)]\n",
    "\n",
    "  # If x has index set m..n, then a[m-1] holds the initial state\n",
    "  # (q0), and a[i+1] holds the state we're in after processing\n",
    "  # x[i].  If a[n] is in F, then we succeed (ie. accept the\n",
    "  # string).\n",
    "  x_range = list(range(0, len(x)))\n",
    "  m = 0\n",
    "  n = len(x)\n",
    "\n",
    "  a = [solver.IntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)]\n",
    "\n",
    "  # Check that the final state is in F\n",
    "  solver.Add(solver.MemberCt(a[-1], F))\n",
    "  # First state is q0\n",
    "  solver.Add(a[m] == q0)\n",
    "  for i in x_range:\n",
    "    solver.Add(x[i] >= 1)\n",
    "    solver.Add(x[i] <= S)\n",
    "\n",
    "    # Determine a[i+1]: a[i+1] == d2[a[i], x[i]]\n",
    "    solver.Add(\n",
    "        a[i + 1] == solver.Element(d2_flatten, ((a[i]) * S) + (x[i] - 1)))\n",
    "\n",
    "\n",
    "def main():\n",
    "\n",
    "  # Create the solver.\n",
    "  solver = pywrapcp.Solver('Nurse rostering using regular')\n",
    "\n",
    "  #\n",
    "  # data\n",
    "  #\n",
    "\n",
    "  # Note: If you change num_nurses or num_days,\n",
    "  #       please also change the constraints\n",
    "  #       on nurse_stat and/or day_stat.\n",
    "  num_nurses = 7\n",
    "  num_days = 14\n",
    "\n",
    "  day_shift = 1\n",
    "  night_shift = 2\n",
    "  off_shift = 3\n",
    "  shifts = [day_shift, night_shift, off_shift]\n",
    "\n",
    "  # the DFA (for regular)\n",
    "  n_states = 6\n",
    "  input_max = 3\n",
    "  initial_state = 1  # 0 is for the failing state\n",
    "  accepting_states = [1, 2, 3, 4, 5, 6]\n",
    "\n",
    "  transition_fn = [\n",
    "      # d,n,o\n",
    "      [2, 3, 1],  # state 1\n",
    "      [4, 4, 1],  # state 2\n",
    "      [4, 5, 1],  # state 3\n",
    "      [6, 6, 1],  # state 4\n",
    "      [6, 0, 1],  # state 5\n",
    "      [0, 0, 1]  # state 6\n",
    "  ]\n",
    "\n",
    "  days = ['d', 'n', 'o']  # for presentation\n",
    "\n",
    "  #\n",
    "  # declare variables\n",
    "  #\n",
    "  x = {}\n",
    "  for i in range(num_nurses):\n",
    "    for j in range(num_days):\n",
    "      x[i, j] = solver.IntVar(shifts, 'x[%i,%i]' % (i, j))\n",
    "\n",
    "  x_flat = [x[i, j] for i in range(num_nurses) for j in range(num_days)]\n",
    "\n",
    "  # summary of the nurses\n",
    "  nurse_stat = [\n",
    "      solver.IntVar(0, num_days, 'nurse_stat[%i]' % i)\n",
    "      for i in range(num_nurses)\n",
    "  ]\n",
    "\n",
    "  # summary of the shifts per day\n",
    "  day_stat = {}\n",
    "  for i in range(num_days):\n",
    "    for j in shifts:\n",
    "      day_stat[i, j] = solver.IntVar(0, num_nurses, 'day_stat[%i,%i]' % (i, j))\n",
    "\n",
    "  day_stat_flat = [day_stat[i, j] for i in range(num_days) for j in shifts]\n",
    "\n",
    "  #\n",
    "  # constraints\n",
    "  #\n",
    "  for i in range(num_nurses):\n",
    "    reg_input = [x[i, j] for j in range(num_days)]\n",
    "    regular(reg_input, n_states, input_max, transition_fn, initial_state,\n",
    "            accepting_states)\n",
    "\n",
    "  #\n",
    "  # Statistics and constraints for each nurse\n",
    "  #\n",
    "  for i in range(num_nurses):\n",
    "    # number of worked days (day or night shift)\n",
    "    b = [\n",
    "        solver.IsEqualCstVar(x[i, j], day_shift) + solver.IsEqualCstVar(\n",
    "            x[i, j], night_shift) for j in range(num_days)\n",
    "    ]\n",
    "    solver.Add(nurse_stat[i] == solver.Sum(b))\n",
    "\n",
    "    # Each nurse must work between 7 and 10\n",
    "    # days during this period\n",
    "    solver.Add(nurse_stat[i] >= 7)\n",
    "    solver.Add(nurse_stat[i] <= 10)\n",
    "\n",
    "  #\n",
    "  # Statistics and constraints for each day\n",
    "  #\n",
    "  for j in range(num_days):\n",
    "    for t in shifts:\n",
    "      b = [solver.IsEqualCstVar(x[i, j], t) for i in range(num_nurses)]\n",
    "      solver.Add(day_stat[j, t] == solver.Sum(b))\n",
    "\n",
    "    #\n",
    "    # Some constraints for this day:\n",
    "    #\n",
    "    # Note: We have a strict requirements of\n",
    "    #       the number of shifts.\n",
    "    #       Using atleast constraints is much harder\n",
    "    #       in this model.\n",
    "    #\n",
    "    if j % 7 == 5 or j % 7 == 6:\n",
    "      # special constraints for the weekends\n",
    "      solver.Add(day_stat[j, day_shift] == 2)\n",
    "      solver.Add(day_stat[j, night_shift] == 1)\n",
    "      solver.Add(day_stat[j, off_shift] == 4)\n",
    "    else:\n",
    "      # workdays:\n",
    "\n",
    "      # - exactly 3 on day shift\n",
    "      solver.Add(day_stat[j, day_shift] == 3)\n",
    "      # - exactly 2 on night\n",
    "      solver.Add(day_stat[j, night_shift] == 2)\n",
    "      # - exactly 1 off duty\n",
    "      solver.Add(day_stat[j, off_shift] == 2)\n",
    "\n",
    "  #\n",
    "  # solution and search\n",
    "  #\n",
    "  db = solver.Phase(day_stat_flat + x_flat + nurse_stat,\n",
    "                    solver.CHOOSE_FIRST_UNBOUND, solver.ASSIGN_MIN_VALUE)\n",
    "\n",
    "  solver.NewSearch(db)\n",
    "\n",
    "  num_solutions = 0\n",
    "  while solver.NextSolution():\n",
    "    num_solutions += 1\n",
    "\n",
    "    for i in range(num_nurses):\n",
    "      print('Nurse%i: ' % i, end=' ')\n",
    "      this_day_stat = defaultdict(int)\n",
    "      for j in range(num_days):\n",
    "        d = days[x[i, j].Value() - 1]\n",
    "        this_day_stat[d] += 1\n",
    "        print(d, end=' ')\n",
    "      print(\n",
    "          ' day_stat:', [(d, this_day_stat[d]) for d in this_day_stat], end=' ')\n",
    "      print('total:', nurse_stat[i].Value(), 'workdays')\n",
    "    print()\n",
    "\n",
    "    print('Statistics per day:')\n",
    "    for j in range(num_days):\n",
    "      print('Day%2i: ' % j, end=' ')\n",
    "      for t in shifts:\n",
    "        print(day_stat[j, t].Value(), end=' ')\n",
    "      print()\n",
    "    print()\n",
    "\n",
    "    # We just show 2 solutions\n",
    "    if num_solutions >= 2:\n",
    "      break\n",
    "\n",
    "  solver.EndSearch()\n",
    "  print()\n",
    "  print('num_solutions:', num_solutions)\n",
    "  print('failures:', solver.Failures())\n",
    "  print('branches:', solver.Branches())\n",
    "  print('WallTime:', solver.WallTime(), 'ms')\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
